package com.luzhikun.servlet;

import com.luzhikun.domain.User;
import com.luzhikun.service.IUserService;
import com.luzhikun.service.impl.IUserServiceImpl;
import com.luzhikun.util.ServiceFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "loginServlet",value = "/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String username = request.getParameter("username");
        String password=request.getParameter("password");
        System.out.println(username);
        System.out.println(password);

        // 创建代理对象
        IUserService userService= (IUserService) ServiceFactory.getService(new IUserServiceImpl());
        String msg="";
        User user = userService.loginUser(username);
        System.out.println(user);

        if (user!=null){
            // 转到主界面
             request.getRequestDispatcher("/mainServlet").forward(request,response);
        }
        else {
            msg="您的账户或密码错误";
            request.setAttribute("error",msg);
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
